# This test script places the input at eee and halfnhalf and 
# then performs the same service as sharpen.py.
# This should show of the data locality considerations done in
# the scheduler.

from __future__ import with_statement
import sys
import scavenger
from scavenger import Scavenger
from time import sleep, time

# Check command line args.
if len(sys.argv) < 2:
    print 'Usage: sharpen_locality.py imagefile peer [iterations]'
    sys.exit(1)

# Read in the image file.
with open(sys.argv[1], 'rb') as infile:
    image = infile.read()

# Fetch the name of the peer to send the image to.
spiked_peer = sys.argv[2]

# Check whether a number of test iterations is given.
iterations = 1
if '-i' in sys.argv:
    iterations = int(sys.argv[sys.argv.index('-i') + 1])

# Check whether a scheduler has been specified.
scheduler = 'basic'
if '-s' in sys.argv:
    scheduler = sys.argv[sys.argv.index('-s') + 1]

# Sleep for a little while to make sure that we discover
# the available surrogates.
sleep(2.0)

# Place the input data at the chosen peer.
peers = Scavenger.get_peers()
found_him = False
for peer in peers:
    if peer.name == spiked_peer:
        found_him = True
        if not Scavenger.has_service(peer, 'std.rdh.store'):
            Scavenger.install_service(peer, 'std.rdh.store', """
def perform(image):
    return image
""")
        data_handle = Scavenger.perform_service(peer, 'std.rdh.store', {'image':image}, store=True)
        data_handle.retain = True
        Scavenger.retain_data(data_handle)
        print 'just got spiked!'
if not found_him:
    raise Exception('Unable to find the peer')

@scavenger.scavenge
def sharpen(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    factor = 1.0 + float(factor)
    sharpened_image = ImageEnhance.Sharpness(pil_image).enhance(factor)
    sio = StringIO()
    sharpened_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.dcscavenge('len(#0)', 100)
def sharpen_dc(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    factor = 1.0 + float(factor)
    sharpened_image = ImageEnhance.Sharpness(pil_image).enhance(factor)
    sio = StringIO()
    sharpened_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()
    
# Choose the function to call - based on the scheduler chosen.
function = None
if scheduler == 'basic':
    function = sharpen
elif scheduler == 'dc':
    function = sharpen_dc
elif scheduler == 'gprofile':
    function = sharpen_gprofile
elif scheduler == 'decomp':
    function = sharpen_decomp
else:
    raise Exception('Unknown scheduler.')

# Run the test!
for x in range(0, iterations):
    start = time()
#    try:
    result = function(data_handle, 1.0)
#    except:
#        print '-1',
    stop = time()
    print stop - start

# Write the result for possible inspection.
with open('result.jpg', 'wb') as outfile:
    outfile.write(result)

scavenger.shutdown()
